package com.example.core.latch;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.context.ApplicationContext;

public class RedissonLeaderLatch implements Latch {

    private ApplicationContext applicationContext;

    private RedissonClient redissonClient;

    private RLock rLock;

    private String lockKey;

    private LeaderLatchListener listener;

    private Thread thread;

    public RedissonLeaderLatch(ApplicationContext applicationContext, String lockKey, LeaderLatchListener listener) {
        this.applicationContext = applicationContext;
        this.lockKey = lockKey;
        this.listener = listener;
        this.redissonClient = applicationContext.getBean(RedissonClient.class);
    }

    @Override
    public void start() {
        this.thread = new Thread(new Runnable() {
            @Override
            public void run() {
                rLock = redissonClient.getLock(lockKey);
                rLock.lock();
                listener.isLeader();
            }
        });
        this.thread.start();
    }

    @Override
    public void stop() {
        if (this.rLock != null) {
            this.rLock.unlock();
        }
        if (this.thread.isAlive()) {
            this.thread.interrupt();
        }
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public RedissonClient getRedissonClient() {
        return redissonClient;
    }

    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    public RLock getrLock() {
        return rLock;
    }

    public void setrLock(RLock rLock) {
        this.rLock = rLock;
    }

    public String getLockKey() {
        return lockKey;
    }

    public void setLockKey(String lockKey) {
        this.lockKey = lockKey;
    }

    public LeaderLatchListener getListener() {
        return listener;
    }

    public void setListener(LeaderLatchListener listener) {
        this.listener = listener;
    }

    public Thread getThread() {
        return thread;
    }

    public void setThread(Thread thread) {
        this.thread = thread;
    }
}
